package com.itheima.aop;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class workAOP {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    // 切 Controller的 login 方法
    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        EmpLoginLog logEntry = new EmpLoginLog();
        logEntry.setLoginTime(LocalDateTime.now());



        Object result = null;

        try {
            //设置扽古用户的信息
            setUserInfo(logEntry,joinPoint);
            result = joinPoint.proceed();
            setJwt(logEntry,result);
            //解析登录的结果
        } catch (Exception e) {
            logEntry.setIsSuccess((short) 0);
            throw e;
        } finally {
            logEntry.setCostTime(System.currentTimeMillis()- start);
            empLoginLogMapper.insert(logEntry);
        }
        return result;
    }
    //设置令牌jwt，只有成功时有
    private void setJwt(EmpLoginLog logEntry, Object result) {
        if (result instanceof Result) {
           Result r = (Result) result;
           if (r.getCode() == 1){
               logEntry.setIsSuccess((short) 1);
               logEntry.setJwt(((LoginInfo) r.getData()).getToken());
           }else {
               logEntry.setIsSuccess((short) 0);
           }
        }
    }
//给log对象设置username和password
    private void setUserInfo(EmpLoginLog logEntry, ProceedingJoinPoint joinPoint) {
        //参数只有一个，只使用下标就行
        Object arg = joinPoint.getArgs()[0];
        Emp emp = (Emp) arg;
        logEntry.setUsername(emp.getUsername());
        logEntry.setPassword(emp.getPassword());
    }
}